<template>
    <el-dialog v-model="dialogFormVisible" :title="title" @close="closeDialog" style="width:650px;">
        <el-form :model="addApproveForm" ref="addBaseTaskRef" :rules="addBaseTaskrules">
            <el-form-item label="审批备注" :label-width="formLabelWidth" prop="title">
                <el-input v-model="addApproveForm.remark" autocomplete="off" ref="name" placeholder="请填写备注"></el-input>
            </el-form-item>
            <!-- :rules="[ { required: element.required, message: element.message },]" -->
            <!-- <el-form-item label="签名" :label-width="formLabelWidth" prop="title">
                <div style="border: 1px solid black;">
                    <esign class="esignature" ref="esign" :lineWidth="lineWidth" :lineColor="lineColor"
                        :bgColor="bgColor" :isEdit="isEdit" />
                </div>

                <el-button type="small" @click="handleReset(index)">清空签名</el-button>
                <el-button type="small" @click="handleGenerate(index)">使用签名</el-button>
            </el-form-item> -->
            <!-- <el-form-item label="上传签名" :label-width="formLabelWidth" prop="imgUrl">
                <img v-if="addApproveForm.imgUrl" :src="addApproveForm.imgUrl" class="name_img" ref="imageElement">
                <el-upload ref="uploadRef" class="upload-demo" :on-change="changeFileHandle" :auto-upload="false"
                    :show-file-list="false">
                    <template #trigger>
                        <el-button type="primary">{{ addApproveForm.imgUrl ? '重新上传' : '上传图片' }}</el-button>
                    </template>
</el-upload>
</el-form-item> -->
            <el-form-item label="上传签名" :label-width="formLabelWidth" prop="imgUrl">
                <img v-if="addApproveForm.imgUrl" :src="addApproveForm.imgUrl" class="name_img" ref="imageElement">
                <el-upload ref="uploadRef" class="upload-demo" :on-change="handleFileChangedata" :auto-upload="false"
                    :show-file-list="false">
                    <template #trigger>
                        <el-button type="primary">{{ addApproveForm.imgUrl ? '重新上传' : '上传图片' }}</el-button>
                    </template>
                </el-upload>
            </el-form-item>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="cancel()">取消</el-button>
                <el-button type="primary" @click="save('审批')">审批</el-button>
                <el-button type="primary" @click="save('驳回')">驳回</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
import { ref } from "vue";
import { httpService } from "@/utils/httpService";
import { ElMessage, ElForm } from "element-plus";
import { vxRule } from "@/utils/validator";
import esign from "../../components/assets/esign.vue";

export default {
    name: "AddBaseAddress",
    components: { ElForm, ElMessage, esign },
    data() {
        return {
            dialogFormVisible: ref(false),
            formLabelWidth: "80px",
            title: "",
            personnelType: "",
            id: '',
            projectId: '',
            teacherList: [],
            quarter: "",
            user: "",
            addApproveForm: {
                remark: "",
                imgUrl: '',
                imgFile: '',
            },
            lineWidth: 3,
            lineColor: "#000000",
            bgColor: "transparent",
            resultImg: "",
            isEdit: true,
            isCrop: true,
            // 校验规则
            addBaseTaskrules: {
                // remark: vxRule(true, null, "blur"),
                imgUrl: vxRule(true, null, "blur"),
            },
        };
    },
    mounted() {
        // this.getCurrentQuarter()
        this.getEsign()
        this.user = JSON.parse(sessionStorage.getItem("user"))
    },
    methods: {
        closeDialog() {
            this.clear();
        },
        cancel() {
            this.dialogFormVisible = false;
            this.clear();
        },

        clear() {
            this.dialogFormVisible = false;
            //清空form
            this.id = ""

            this.addApproveForm.remark = ""
            this.addApproveForm.content = ""
        },
        handleReset(index) {
            this.$refs.esign.reset();
        },
        handleGenerate(index) {
            this.$refs.esign
                .generate()
                .then((res) => {
                    console.log(res);
                })
                .catch((err) => {
                    alert(err);
                });
        },
        save(str) {
            console.log(this.id);
            this.$refs.addBaseTaskRef.validate((valid) => {
                if (valid) {
                    let params = new FormData(); //创建一个form对象,必须是form对象否则后端接受不到数据
                    params.append("remark", this.addApproveForm.remark);
                    params.append("id", this.id);
                    params.append("projectId", this.projectId);
                    if (str == "审批") {
                        params.append("status", 1);
                    } else if ("驳回") {
                        params.append("status", 2);
                    }
                    httpService("/javaApi/faProjectApprove/edit", params, "post").then(
                        (data) => {
                            if (data.code == 200) {
                                ElMessage.success("操作完成");
                                this.clear();
                                //刷新父组件的数据
                                this.$parent.getMyApproveList();
                            } else {
                                ElMessage.error("操作失败");
                            }
                        }
                    );
                } else {
                    return false;
                }
            });
        },


        handleFileChangedata(value) {
            const file = value.raw
            if (!file) return;
            const reader = new FileReader();
            reader.onload = (e) => {
                const img = new Image();
                img.onload = () => {
                    let canvas = document.createElement('canvas');
                    let ctx = canvas.getContext('2d');
                    canvas.width = img.height;
                    canvas.height = img.width;
                    ctx.fillStyle = '#FFFFFF';
                    ctx.fillRect(0, 0, canvas.width, canvas.height);
                    if (img.height > img.width) {
                        // canvas.width = img.height;
                        // canvas.height = img.width;
                        ctx.rotate(-Math.PI / 2); // 逆时针旋转90度
                        ctx.drawImage(img, (-img.height / 12) * 9, 0);

                        canvas.toBlob((blob) => {
                            const rotatedFile = new File([blob], file.name, { type: file.type });
                            console.log(123123, rotatedFile);
                            this.handel(rotatedFile)
                            this.changeFileHandle(rotatedFile)
                        }, file.type);
                    } else {
                        // canvas.width = img.width;
                        // canvas.height = img.height;
                        // ctx.drawImage(img, 0, 0);
                        this.changeFileHandle(file)
                    }
                };

                // 将读取到的文件内容设置为图片源
                img.src = e.target.result;
            };

            // // 读取文件内容
            reader.readAsDataURL(file);
        },

        changeFileHandle(value) {
            const reader = new FileReader();
            reader.onload = (e) => {
                const img = new Image();
                const timeData = new Date().getTime();

                img.src = e.target.result;
                img.onload = () => {
                    const canvas = document.createElement('canvas');
                    const ctx = canvas.getContext('2d');
                    canvas.width = 55;
                    canvas.height = 35;
                    ctx.fillStyle = '#FFFFFF';
                    ctx.fillRect(0, 0, canvas.width, canvas.height);
                    const maxWidth = 55; // 设置最大宽度
                    const maxHeight = 35; // 设置最大高度
                    let width = img.width;
                    let height = img.height;
                    if (width > height) {
                        if (width > maxWidth) {
                            height *= maxWidth / width;
                            width = maxWidth;
                        }
                    } else {
                        if (height > maxHeight) {
                            width *= maxHeight / height;
                            height = maxHeight;
                        }
                    }
                    // canvas.width = width;
                    // canvas.height = height;
                    ctx.drawImage(img, 0, 0, width, height);
                    canvas.toBlob((blob) => {
                        const fileimg = new File([blob], `${timeData}${this.user.teacherNumber}.png`, { type: 'image/jpeg' })
                        console.log(22222, fileimg);
                        this.setEsign(fileimg)
                        // this.addAppForm.imgUrl = img.src
                    }, 'image/jpeg', 1); // 0.8 是压缩质量，可根据需要调整
                };

            };
            reader.readAsDataURL(value);
        },


        // handleFileChangedata(value) {
        //     const file = value.raw
        //     if (!file) return;
        //     const reader = new FileReader();
        //     reader.onload = (e) => {
        //         const img = new Image();
        //         img.onload = () => {
        //             let canvas = document.createElement('canvas');
        //             let ctx = canvas.getContext('2d');
        //             canvas.width = img.height;
        //             canvas.height = img.width;
        //             ctx.fillStyle = '#FFFFFF';
        //             ctx.fillRect(0, 0, canvas.width, canvas.height);
        //             alert(img.height + "...." + img.width)
        //             if (img.height > img.width) {
        //                 // alert(1)
        //                 // canvas.width = img.height;
        //                 // canvas.height = img.width;
        //                 ctx.rotate(-Math.PI / 2); // 逆时针旋转90度
        //                 ctx.drawImage(img, (-img.height / 12) * 9, 0);
        //                 canvas.toBlob((blob) => {
        //                     const rotatedFile = new File([blob], file.name, { type: file.type });
        //                     this.changeFileHandle(rotatedFile)
        //                 }, file.type);
        //             } else {
        //                 // alert(2)
        //                 // canvas.width = img.width;
        //                 // canvas.height = img.height;
        //                 // ctx.drawImage(img, 0, 0);
        //                 this.changeFileHandle(file)
        //             }
        //             // canvas.toBlob((blob) => {
        //             //     const rotatedFile = new File([blob], file.name, { type: file.type });
        //             //     this.changeFileHandle(rotatedFile)
        //             // }, file.type);
        //         };

        //         // 将读取到的文件内容设置为图片源
        //         img.src = e.target.result;
        //     };

        //     // 读取文件内容
        //     reader.readAsDataURL(file);
        // },
        // aaaaa(file) {
        //     const reader = new FileReader();
        //     reader.onload = (e) => {
        //         const img = new Image();
        //         img.src = e.target.result;
        //         console.log(img.src);
        //     }
        //     reader.readAsDataURL(file);
        // },

        // changeFileHandle(value) {
        //     const reader = new FileReader();
        //     reader.onload = (e) => {
        //         const img = new Image();
        //         const timeData = new Date().getTime();

        //         img.src = e.target.result;
        //         img.onload = () => {
        //             const canvas = document.createElement('canvas');
        //             const ctx = canvas.getContext('2d');
        //             // let compressedImage = ''
        //             canvas.width = 55;
        //             canvas.height = 35;
        //             ctx.fillStyle = '#FFFFFF';
        //             ctx.fillRect(0, 0, canvas.width, canvas.height);
        //             const maxWidth = 55; // 设置最大宽度
        //             const maxHeight = 35; // 设置最大高度
        //             let width = img.width;
        //             let height = img.height;
        //             if (width > height) {
        //                 if (width > maxWidth) {
        //                     height *= maxWidth / width;
        //                     width = maxWidth;
        //                 }
        //             } else {
        //                 if (height > maxHeight) {
        //                     width *= maxHeight / height;
        //                     height = maxHeight;
        //                 }
        //             }
        //             canvas.width = width;
        //             canvas.height = height;
        //             ctx.drawImage(img, 0, 0, width, height);
        //             canvas.toBlob((blob) => {
        //                 const fileimg = new File([blob], `${timeData}${this.user.teacherNumber}.png`, { type: 'image/jpeg' })
        //                 // console.log('file', fileimg);
        //                 // this.addApproveForm.imgFile = fileimg
        //                 this.setEsign(fileimg)

        //                 // this.addApproveForm.imgUrl = img.src

        //                 // console.log(11111111, width, height);
        //             }, 'image/jpeg', 1); // 0.8 是压缩质量，可根据需要调整
        //         };

        //     };
        //     reader.readAsDataURL(value);
        // },

        getEsign() {
            httpService("/javaApi/baseTeacher/getEsign", {}, "get").then(
                (data) => {
                    if (data.object) {
                        this.addApproveForm.imgUrl = "https://wx.zhengzhong.cn" + data.object
                        // this.addApproveForm.imgUrl = "http://192.168.9.20" + data.object
                    } else {
                        this.addApproveForm.imgUrl = ""
                    }
                    // this.addApproveForm.imgUrl = "https://wx.zhengzhong.cn" + data.object
                    // console.log(this.addApproveForm.imgUrl);
                }
            );
        },
        setEsign(imgFile) {
            let params = new FormData()
            params.append("file", imgFile)
            httpService("/javaApi/baseTeacher/setEsign", params, "post").then(
                (data) => {
                    if (data.object) {
                        this.addApproveForm.imgUrl = "https://wx.zhengzhong.cn" + data.object
                        // this.addApproveForm.imgUrl = "http://192.168.9.20" + data.object
                    } else {
                        this.addApproveForm.imgUrl = ""
                    }
                    // this.addApproveForm.imgUrl = "https://wx.zhengzhong.cn" + data.object + '.png'
                }
            );
        },
    },
};
</script>
<style scoped>
.name_img {
    width: 100px;
    margin-right: 20px;
}

.el-dialog__header {
    padding: var(--el-dialog-padding-primary);
    padding-bottom: 10px;
    border-bottom: 1px solid #dedede;
    margin-bottom: 15px;
}
</style>